package com.example.micrweb.front.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.example.common.constants.RedisKey;
import com.example.common.util.HttpClientUtils;
import com.example.micrweb.front.config.smsConfig;
import com.example.micrweb.front.service.SmsService;
import io.netty.util.internal.StringUtil;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.RandomStringUtils;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.util.EntityUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.security.MessageDigest;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;


/**
 * @description: 注册短信验证码
 * @author: uu
 * @data: 2023/7/15 下午 03:48
 * @version: v1.0
 */
@Service
public class SmsServiceImpl implements SmsService {

    @Resource
    private smsConfig sms;
    @Resource
    private StringRedisTemplate stringRedisTemplate;


    /*验证码验证*/
    @Override
    public boolean checkSmsCode(String phone, String code) {
        String key = RedisKey.KEY_SMS_CODE_REG + phone;

        if (stringRedisTemplate.hasKey(key)){
            // 从redis中拿到短信验证码
            String querySmsCode = stringRedisTemplate.boundValueOps(key).get();
            if (code.equals(querySmsCode)){
                return true;
            }
        }
        return false;
    }

    /*发送短信验证码*/
    @Override
    public boolean sendSms(String phone) {
        String random = RandomStringUtils.randomNumeric(4);
        boolean send = false;
        String url = sms.getUrl();
        String appcode = sms.getAppcode();

        Map<String, String> header = new HashMap<>();
        header.put("Authorization", "APPCODE " + appcode);
        header.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

        Map<String, Object> params = new HashMap<>();
        params.put("content", "code:"+random);
        params.put("phone_number", phone);
        params.put("template_id", sms.getTemplate_id());
        try {
            // 发送短信
            String resp = HttpClientUtils.doPost(url, header, params);
            if (StringUtils.isNotBlank(resp)){
                System.out.println(JSONObject.parseObject(resp));
                if ("OK".equalsIgnoreCase(JSONObject.parseObject(resp).getString("status"))){
                    // 验证码发送成功，将验证码存到redis中
                    send = true;
                    stringRedisTemplate.opsForValue().set(RedisKey.KEY_SMS_CODE_REG+phone, random, Duration.ofMinutes(3));
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return send;
    }


    // 计算并获取CheckSum
    public static String getCheckSum(String appSecret, String nonce, String curTime) {
        return encode("sha1", appSecret + nonce + curTime);
    }

    // 计算并获取md5值
    public static String getMD5(String requestBody) {
        return encode("md5", requestBody);
    }

    private static String encode(String algorithm, String value) {
        if (value == null) {
            return null;
        }
        try {
            MessageDigest messageDigest
                    = MessageDigest.getInstance(algorithm);
            messageDigest.update(value.getBytes());
            return getFormattedText(messageDigest.digest());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    private static String getFormattedText(byte[] bytes) {
        int len = bytes.length;
        StringBuilder buf = new StringBuilder(len * 2);
        for (int j = 0; j < len; j++) {
            buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
            buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
        }
        return buf.toString();
    }
    private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
}
